﻿using heyirunde.Models;
using heyirunde.variable;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using heyirunde.wx;
using System.Xml;
using System.Drawing;
using System.Net;
using ImageProcessor;
using ImageProcessor.Imaging.Formats;

namespace heyirunde
{
    /// <summary>
    /// WXinterface 的摘要说明
    /// </summary>
    public class WXinterface : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            string token = "hyrd701888";

            string echoString = HttpContext.Current.Request.QueryString["echoStr"];
            string signature = HttpContext.Current.Request.QueryString["signature"];
            string timestamp = HttpContext.Current.Request.QueryString["timestamp"];
            string nonce = HttpContext.Current.Request.QueryString["nonce"];
            if (CheckSignature(token, signature, timestamp, nonce))
            {
                if (!string.IsNullOrEmpty(echoString))
                {
                    HttpContext.Current.Response.Write(echoString);
                    HttpContext.Current.Response.End();
                }
            }


            ///获取用户是否关注 与 取消 


            using (var db = new SqlSugarClient(DBHelper.connectionString))
            {




                JsonHelper jsonHelper = new JsonHelper();

                Stream stream = HttpContext.Current.Request.InputStream;
                Byte[] postBytes = new Byte[stream.Length];
                stream.Read(postBytes, 0, (Int32)stream.Length);
                string postString = Encoding.UTF8.GetString(postBytes);

                if (!string.IsNullOrEmpty(postString))
                {
                    //封装请求类

                    XmlDocument requestDocXml = new XmlDocument();
                    requestDocXml.LoadXml(postString);
                    XmlElement rootElement = requestDocXml.DocumentElement;


                    string ToUserName = rootElement.SelectSingleNode("ToUserName").InnerText.ToString();//开发者 微信号
                    string FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText.ToString();//发送方帐号（一个OpenID）
                    string CreateTime = rootElement.SelectSingleNode("CreateTime").InnerText.ToString();//消息创建时间
                    string MsgType = rootElement.SelectSingleNode("MsgType").InnerText.ToString();//消息类型，event
                    // string Event = rootElement.SelectSingleNode("Event").InnerText.ToString();
                    string EventKey = rootElement.SelectSingleNode("EventKey").InnerText.ToString(); // 关注的时候推送的例子  qrscene_N3YIA2   消息的推送是自定义的 haibao_tui

                    //有新用户关注了公众号 
                    //判断用户是否存在
                    T_user singleOrDefault = db.Queryable<T_user>().SingleOrDefault(it => it.openId == FromUserName && it.isdel == 0);

                    if (singleOrDefault == null)
                    {
                        string guid = Guid.NewGuid().ToString("N");
                        //用户不存在  获取用户的基本信息
                        RestClient client6 = new RestClient("https://api.weixin.qq.com/cgi-bin/user/info");
                        RestRequest request6 = new RestRequest(Method.GET);
                        request6.AddQueryParameter("access_token", wxconfig.getToken());
                        request6.AddQueryParameter("openid", FromUserName);
                        request6.AddQueryParameter("lang", "zh_CN");
                        IRestResponse res6 = client6.Execute(request6);
                        JObject oj = (JObject)JsonConvert.DeserializeObject(res6.Content);
                        T_user user = new T_user()
                        {
                            userGuid = guid,
                            openId = FromUserName,
                            nickName = oj["nickname"].ToString(),
                            photoimg = oj["headimgurl"].ToString(),
                            createTime = DateTime.Now,
                            isdel = 0,
                            code = generateRandomString(6),
                        };
                        wxconfig config = new wxconfig();
                        ///给 姜总发推送                
                        string openIds = "oEhd9jjlRC_hsrKimSCpTPSxpcZk";
                        config.sendmessage_zhuce(openIds, user.nickName.Trim());
                        int insert = db.Insert(user).ObjToInt();



                          

                       // string EventKey = rootElement.SelectSingleNode("EventKey").InnerText.ToString();//qrscene_N3YIA2 
                        if (EventKey.Contains("qrscene"))
                        {
                            EventKey = EventKey.Substring(8, EventKey.Length - 8);
                        }

                        if (insert > 0 && EventKey.Length != 0)
                        {

                            //绑定 邀请人 
                            T_user userobj = db.Queryable<T_user>().SingleOrDefault(it => it.code == EventKey && it.isdel == 0);
                            if (userobj != null)
                            {
                                //绑定邀请人
                                InviteCode invite1 = new InviteCode()
                                {
                                    userGuid = guid,
                                    code = EventKey,
                                    obj_userGuid = userobj.userGuid.Trim(),
                                    createTime = DateTime.Now
                                };
                                db.Insert(invite1);

                                //推广获得的积分
                                int tuiguang = Peizhi.tuiguang;
                                User_record user1 = new User_record()
                                {
                                    userGuid = userobj.userGuid.Trim(),
                                    jifen = tuiguang,
                                    createTime = DateTime.Now,
                                    BeiZhu = "邀请",
                                    type = 1,
                                };
                                db.Insert(user1);
                                //增加总积分
                                User_score scroe_user = db.Queryable<User_score>().SingleOrDefault(it => it.userGuid == userobj.userGuid);

                                db.Update<User_score>(new { jiFen = scroe_user.jiFen + tuiguang }, it => it.userGuid == userobj.userGuid);

                            }
                        }


                        string textpl = string.Empty;
                        textpl = "<xml>" +
                                  "<ToUserName><![CDATA[" + FromUserName.ToString() + "]]></ToUserName>" +
                                 "<FromUserName><![CDATA[" + ToUserName.ToString() + "]]></FromUserName>" +
                                 "<CreateTime>" + jsonHelper.ToDateTime(DateTime.Now) + "</CreateTime>" +
                                  "<MsgType><![CDATA[text]]></MsgType>" +
                                  "<Content><![CDATA[" + "欢迎关注<a href = 'http://heyirunde.com/'> 和易润德 </a> 服务号，做中国最卓越的咨询服务平台，助力企业发展与增值！15年服务经验，百人团队,千家企业成功案例，您值得信赖\n\n" +

       "1.电话：13137715079\n\n" +

    "2.点击 <a href='http://eqidd.com/wx/share.html'>我要推广</a>，您的专属海报，超额学分，分享平台发展，可在商城兑换超值服务与商品，还有神秘大礼包。\n\n" +

    "3.点我 <a href='https://w.url.cn/s/AwJBlZj'> 签到 </a>：获取更多学分，连续签到更有神秘礼包！\n\n" +

    "4.<a href='http://eqidd.com/wx/shopping.html'> 学分商城：</a> 是时候展现自己的实力了！\n\n" + "]]></Content>" +
    "</xml>";

                        XmlDocument xml = new XmlDocument();

                        xml.LoadXml(textpl);
                        context.Response.Write(textpl);



                        if (!string.IsNullOrEmpty(textpl))
                        {
                            HttpContext.Current.Response.Write(xml);
                            HttpContext.Current.Response.End();
                        }
                        else
                        {
                            HttpContext.Current.Response.Write(" ");
                            HttpContext.Current.Response.End();
                        }




                    }







                    if (EventKey.Trim() == "haibao_tui")
                    {


                      

                        ////将图片上传到微信服务器并发送给用户

                        string imagePath = Draw(CreateTempQRCode(singleOrDefault.code), singleOrDefault.photoimg, singleOrDefault.nickName,singleOrDefault.openId);
                        RestClient client_upload = new RestClient("https://api.weixin.qq.com/cgi-bin/media/upload");
                        RestRequest request_upload = new RestRequest(Method.POST);
                        request_upload.AddParameter("access_token", wxconfig.getToken());
                        request_upload.AddParameter("type", "image");
                        request_upload.AddParameter("media", "filename");

                        request_upload.AddFile("file", imagePath);

                        IRestResponse res = client_upload.Execute(request_upload);
                        JObject oj_up = (JObject)JsonConvert.DeserializeObject(res.Content);

                        string media_id = (string)oj_up["media_id"];


                        WX_UserGuanZhu guanzhu = new WX_UserGuanZhu()
                        {
                            ToUserName = ToUserName,
                            FromUserName = FromUserName,
                            CreateTime = CreateTime,
                            MsgType = "测试",
                            Event = " ",
                            EventKey = EventKey,
                            Ticket = media_id

                        };

                        db.Insert(guanzhu);



                        if (!string.IsNullOrEmpty(media_id))
                        {

                            string resxml = "<xml><ToUserName><![CDATA[" + FromUserName.ToString() + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName.ToString() + "]]></FromUserName><CreateTime>" + CreateTime + "</CreateTime><MsgType><![CDATA[image]]></MsgType><Image><MediaId><![CDATA[" + media_id + "]]></MediaId></Image></xml>";


                            /*
                            XmlDocument xml_tui = new XmlDocument();

                            xml_tui.LoadXml(resxml);


                            if (!string.IsNullOrEmpty(resxml))
                            {
                                HttpContext.Current.Response.Write(xml_tui);
                                HttpContext.Current.Response.End();
                            }
                            else
                            {
                                HttpContext.Current.Response.Write("");
                                HttpContext.Current.Response.End();
                            }*/

                            HttpContext.Current.Response.Write(resxml);
                            HttpContext.Current.Response.End();
                            return ;
                        }
                      //  LogHelper.WriteLog(typeof(WechatController), "上传专属推广图片素材失败" + result);

                    }

                      






                    return;


                }


                string textp2 = string.Empty;
                textp2 = "<xml>" +                      
                       
                          "<Content><![CDATA[" + "<a href = 'http://heyirunde.com'> 和易润德 </a> 服务号，做中国最卓越的咨询服务平台，助力企业发展与增值！15年服务经验，百人团队,千家企业成功案例，您值得信赖\n\n" +

"1.电话：13137715079\n\n" +

"2.点击 <a href='http://eqidd.com/wx/share.html'>我要推广</a>，您的专属海报，超额学分，分享平台发展，可在商城兑换超值服务与商品，还有神秘大礼包。\n\n" +

"3.点我 <a href='https://w.url.cn/s/AwJBlZj'> 签到 </a>：获取更多学分，连续签到更有神秘礼包！\n\n" +

"4.<a href='http://eqidd.com/wx/shopping.html'> 学分商城：</a> 是时候展现自己的实力了！\n\n" + "]]></Content>" +
"</xml>";

                XmlDocument xml2 = new XmlDocument();

                xml2.LoadXml(textp2);
                context.Response.Write(textp2);



                if (!string.IsNullOrEmpty(textp2))
                {
                    HttpContext.Current.Response.Write(xml2);
                    HttpContext.Current.Response.End();
                }
                else
                {
                    HttpContext.Current.Response.Write("");
                    HttpContext.Current.Response.End();
                }



             







                return;



            }
        }



        /// <summary>
        /// 获取临时二维码ticket  haibao_tui
        /// </summary>
        /// <param name="scene_str">场景值ID openid做场景值ID</param>
        /// <returns></returns>
        public static string CreateTempQRCode(string scene_str)
        {
            RestClient client = new RestClient("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + wxconfig.getToken());

            RestRequest request = new RestRequest();
            request.Method = Method.POST;
            request.AddJsonBody(new
            {
                action_name = "QR_LIMIT_STR_SCENE",
                action_info = new
                {
                    scene = new { scene_str = scene_str }
                }
            }
        );
            IRestResponse res = client.Execute(request);

            JObject jobect = (JObject)JsonConvert.DeserializeObject(res.Content);

            string ticket = (string)jobect["ticket"];



          

            if (string.IsNullOrEmpty(ticket))
            {

                return " ";
            }
            return ticket;
        }




        /// <summary>
        /// 生成带二维码的专属推广图片
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string Draw(string ticket, string headimgurl, string nickname,string openId)
        {
            //背景图片
            string path = HttpContext.Current.Server.MapPath("/img/27.jpg");
            string path1 = HttpContext.Current.Server.MapPath("/img/26.jpg");
            Random rom = new Random();
           int num = rom.Next(0,2);
            if(num==0)
            {

            }else if(num==1)
            {
                path = path1;
            }else
            {

            }



            System.Drawing.Image imgSrc = System.Drawing.Image.FromFile(path);

            //处理二维码图片大小 240*240px
            System.Drawing.Image qrCodeImage = ReduceImage("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket, 240, 240);

            //处理头像图片大小 100*100px
            Image titleImage = ReduceImage(headimgurl, 200, 200);

            using (Graphics g = Graphics.FromImage(imgSrc))
            {
                //画专属推广二维码
                g.DrawImage(qrCodeImage, new Rectangle(imgSrc.Width - qrCodeImage.Width - 30,
                imgSrc.Height - qrCodeImage.Height - 30,
                qrCodeImage.Width,
                qrCodeImage.Height),
                0, 0, qrCodeImage.Width, qrCodeImage.Height, GraphicsUnit.Pixel);

                //画头像
                g.DrawImage(titleImage, 30, imgSrc.Height - qrCodeImage.Height, titleImage.Width, titleImage.Height);

                Font font = new Font("宋体", 40, FontStyle.Bold);

                g.DrawString(nickname, font, new SolidBrush(Color.Black), 20, imgSrc.Height - qrCodeImage.Height + titleImage.Height + 8);
            }
            string newpath = @"C:\manager\image\27"+ openId+".jpg";
            ISupportedImageFormat format = new PngFormat { Quality = 70 };
            using (MemoryStream outStream = new MemoryStream())
            {
                // 使用重载初始化ImageFactory以保留EXIF元数据。
                using (ImageFactory imageFactory = new ImageFactory(true))
                {
                    // 加载，调整大小，设置格式和质量并保存图像。
                    imageFactory.Load(imgSrc)
                        .Format(format)
                        .Resize(new Size(540, 1054))

                        .Save(newpath);

                }
                /*

                  ImgManager img = new ImgManager()
                  {
                      userGuid = " ",
                      imgurl = path,
                      miniurl = newpath,
                      width = imgSrc.Width,
                      height = imgSrc.Height,
                      size = " ",
                      type = 1,
                      createTime = DateTime.Now,
                      isdel = 0
                  };
                  db.Insert(img);
                  */
            }

            //  imgSrc.Save(newpath, System.Drawing.Imaging.ImageFormat.Jpeg);
            return newpath;
        }


        /// <summary>
        /// 缩小/放大图片
        /// </summary>
        /// <param name="url">图片网络地址</param>
        /// <param name="toWidth">缩小/放大宽度</param>
        /// <param name="toHeight">缩小/放大高度</param>
        /// <returns></returns>
        public Image ReduceImage(string url, int toWidth, int toHeight)
        {
            WebRequest request = WebRequest.Create(url);
            WebResponse response = request.GetResponse();
            Stream responseStream = response.GetResponseStream();

            Image originalImage = Image.FromStream(responseStream);
            if (toWidth <= 0 && toHeight <= 0)
            {
                return originalImage;
            }
            else if (toWidth > 0 && toHeight > 0)
            {
                if (originalImage.Width < toWidth && originalImage.Height < toHeight)
                    return originalImage;
            }
            else if (toWidth <= 0 && toHeight > 0)
            {
                if (originalImage.Height < toHeight)
                    return originalImage;
                toWidth = originalImage.Width * toHeight / originalImage.Height;
            }
            else if (toHeight <= 0 && toWidth > 0)
            {
                if (originalImage.Width < toWidth)
                    return originalImage;
                toHeight = originalImage.Height * toWidth / originalImage.Width;
            }
            Image toBitmap = new Bitmap(toWidth, toHeight);
            using (Graphics g = Graphics.FromImage(toBitmap))
            {
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.Clear(Color.Transparent);
                g.DrawImage(originalImage,
                   new Rectangle(0, 0, toWidth, toHeight),
                   new Rectangle(0, 0, originalImage.Width, originalImage.Height),
                   GraphicsUnit.Pixel);
                originalImage.Dispose();
                return toBitmap;
            }
        }





        /// <summary>
        /// 获取随机邀请码
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>

        static string generateRandomString(int length)
        {
            Random random = new Random();
            var chars = "ABCDEFGHIJKMNPQRSTUVWXYZ123456789";
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < length; i++)
            {
                int index = random.Next(chars.Length);
                result.Append(chars[index]);
            }
            return result.ToString();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// 验证微信签名
        /// </summary>
        public static bool CheckSignature(string token, string signature, string timestamp, string nonce)
        {
            SteHelper sh = new SteHelper();
            string[] ArrTmp = { token, timestamp, nonce };
            //字典排序
            Array.Sort(ArrTmp);
            //拼接
            string tmpStr = string.Join("", ArrTmp);
            //sha1验证
            //获取
            string hash = sh.Sha1(tmpStr);
            tmpStr = hash.ToLower();
            if (tmpStr == signature)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

    }
}